package org.exez.modules.visitor.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 *
 * 签名相关工具类.
 * Created by dtm 2020-6-6.
 *
 * @author dtm
 */
@Slf4j
public class SignUtils {

  /**
   * 签名的时候不携带的参数
   */
  private static List<String> NO_SIGN_PARAMS = Lists.newArrayList("sign", "key");

  /**
   *
   * @param params        参数信息
   * @param signKey       签名Key
   * @return 签名字符串 string
   */
  public static String createSign(Map<String, String> params, String signKey) {
    SortedMap<String, String> sortedMap = new TreeMap<>(params);

    StringBuilder toSign = new StringBuilder();
    for (String key : sortedMap.keySet()) {
      String value = params.get(key);
      boolean shouldSign = false;
      if (StringUtils.isNotEmpty(value) && !NO_SIGN_PARAMS.contains(key)) {
        shouldSign = true;
      }

      if (shouldSign) {
        toSign.append(key).append("=").append(value).append("&");
      }
    }

    toSign.append("key=").append(signKey);

    return DigestUtils.sha1Hex(toSign.toString()).toUpperCase();
  }

}